package cn.edu.jsu.zjj.controller;


import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.annotation.Type;
import cn.edu.jsu.zjj.common.DeleteRequest;
import cn.edu.jsu.zjj.common.result.PageResult;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.config.JwtProperties;
import cn.edu.jsu.zjj.constant.JwtClaimsConstant;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.constant.UserConstant;
import cn.edu.jsu.zjj.context.BaseContext;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.exception.ThrowUtils;
import cn.edu.jsu.zjj.model.dto.user.*;
import cn.edu.jsu.zjj.model.entity.*;
import cn.edu.jsu.zjj.model.enums.UserRoleEnum;
import cn.edu.jsu.zjj.model.utils.*;
import cn.edu.jsu.zjj.model.vo.LoginUserVO;
import cn.edu.jsu.zjj.model.vo.UserVO;
import cn.edu.jsu.zjj.service.*;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.util.MapUtils;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Api(tags = "员工相关接口")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private OperLogService operLogService;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    BeanSearcher beanSearcher;
    @Autowired
    private UserTitleService userTitleService;
    @Autowired
    private UserWorkService userWorkService;
    @Autowired
    private MajorService majorService;
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/information")
    @ApiOperation(value = "用户信息")
    public void getInformation(HttpServletResponse response, Long userId) throws Exception {
        // 获取用户信息
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getId,userId).eq(User::getIsDelete,0));
        // 获取用户其他数据
//        List<UserTitle> userTitleList = userTitleService.list(new LambdaQueryWrapper<UserTitle>().eq(UserTitle::getUserId,userId).eq(UserTitle::getIsDelete,0));
        List<UserWork> userWorkList = userWorkService.list(new LambdaQueryWrapper<UserWork>().eq(UserWork::getUserId,userId).eq(UserWork::getIsDelete,0));
        UserTitle userTitle = beanSearcher.searchFirst(UserTitle.class, MapUtils.builder().field(UserTitle::getUserId,userId).field(UserTitle::getIsDeleted,0).orderBy(UserTitle::getObtainDate).desc().build());
        // 组装数据
        if (userTitle == null) {
            userTitle = new UserTitle();
        }
        if (userWorkList == null) {
            userWorkList = new ArrayList<>();
        }
        String title = userTitle.getTitle();
        LocalDateTime obtainDate = userTitle.getObtainDate();
        UserFillRequest userFillRequest = new UserFillRequest();
        Optional.ofNullable(user).ifPresent(userFillRequest::setUser);
        Optional.ofNullable(title).ifPresent(userFillRequest::setTitle);
        Optional.ofNullable(obtainDate).ifPresent(userFillRequest::setObtainDate);
        Optional.of(userWorkList).ifPresent(userFillRequest::setUserWorks);
        DocxUtils.modifyDocx(response,userFillRequest);
    }

    @GetMapping("/my")
    @ApiOperation(value = "获取当前登录用户的信息")
    public Result<UserVO> getMyUserInfo() {
        User user = userService.getLoginUser();
        UserVO userVO = userService.getUserVO(user);
        return Result.success(userVO);
    }

    @PostMapping("/password")
    @ApiOperation(value =  "修改密码or重置密码")
    public Result<String> updatePassword(@RequestBody UserUpdatePassword userUpdatePassword) {
        Long userId = userUpdatePassword.getUserId() != null ? userUpdatePassword.getUserId() : userService.getLoginUser().getId();
        User user = userService.getById(userId);
        String oldPassword = null;
        String confirmPassword = null;
        if (!userUpdatePassword.getIsReset()) {
            oldPassword = DigestUtils.md5DigestAsHex(userUpdatePassword.getOldPassword().getBytes());
            confirmPassword = DigestUtils.md5DigestAsHex(userUpdatePassword.getConfirmPassword().getBytes());
        }
        String newPassword = DigestUtils.md5DigestAsHex(userUpdatePassword.getNewPassword().getBytes());
        if (!userUpdatePassword.getIsReset() && !user.getPassword().equals(oldPassword)) {
            return Result.error("旧密码错误");
        }
        if (!userUpdatePassword.getIsReset() && !newPassword.equals(confirmPassword)) {
            return Result.error("两次密码不一致");
        }

        if (!userUpdatePassword.getIsReset() && user.getPassword().equals(newPassword)) {
            return Result.error("新密码不能与旧密码相同");
        }

        user.setPassword(newPassword);
        userService.updateById(user);
        return Result.success("密码修改成功");
    }
    /**
     * 登录测试数据
     * 管理员 —— 工号：105，密码：123456
     * 教师 —— 工号：103，密码：123456
     * PS：所有功能务必先登录再测试，否则报401！！！！！
     *
     * @param userLoginRequest
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "员工登录")
    public Result<LoginUserVO> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        log.info("员工登录：{}", userLoginRequest);

        User user = userService.login(userLoginRequest);


        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);

        // 计算完善度
        int complete = OtherUtils.getFilledFieldsCount(user);
        int total = user.getClass().getDeclaredFields().length;
        DecimalFormat df = new DecimalFormat("#.##%");
        String percentage = df.format((double) complete / total);
        LoginUserVO loginUserVO = LoginUserVO.builder()
                .id(user.getId())
                .avatar(user.getAvatar())
                .name(user.getName())
                .roles(user.getRoles())
//                .roles(JSONUtil.toList(user.getRoles(), String.class))
                .token(token)
                .complete(percentage)
                .required(false)
                .build();
        if(Objects.isNull(user.getDegree())){
            loginUserVO.setRequired(true);
        }
        log.info("登录成功，生成token：{}", token);
        return Result.success(loginUserVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("员工退出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 新增员工
     *
     * @param userAddRequest 包含新增员工信息的请求对象
     * @return 返回操作结果
     */
    @ApiOperation("新增员工（仅管理员）")
    @Type("新增员工")
    @PostMapping
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result save(@RequestBody UserAddRequest userAddRequest) {
        // 新增员工时操作日志记录
        OperLog operLog = userService.setOperLog();
        operLog.setRemark(userService.getLoginUser().getName() + "新增员工：" + userAddRequest.getName());
        operLogService.save(operLog);

        // 新增员工处理逻辑
        log.info("新增员工：{}", userAddRequest);
        User user = new User();


        user.setOperUserId(userService.getLoginUser().getId());
        user.setOperUserName(userService.getLoginUser().getName());
        user.setCreateUserId(userService.getLoginUser().getId());

        // 设置默认密码为 123456 并加密
        String defaultPassword = "123456";
        String encryptPassword = DigestUtils.md5DigestAsHex(defaultPassword.getBytes());
        user.setPassword(encryptPassword);
        if (Objects.equals(userAddRequest.getSex(), "0")) {
            user.setAvatar("https://hmleadnews5283.oss-cn-beijing.aliyuncs.com/boy-1729611663455.jpg");
        } else if (Objects.equals(userAddRequest.getSex(), "1")) {
            user.setAvatar("https://hmleadnews5283.oss-cn-beijing.aliyuncs.com/girl-1729611635266.jpg");
        } else {
            user.setAvatar("https://zjj.jsu.edu.cn/u/cms/www/202201/11000204fyke.png");
        }
        user.setSex(userAddRequest.getSex());
        String phoneNumber = userAddRequest.getPhoneNumber();
        String email = userAddRequest.getEmail();

        //设置必填
        user.setName(userAddRequest.getName());
        if(userService.getLoginUser().getRoles().contains(UserConstant.EDU_ADMIN_ROLE)||userService.getLoginUser().getRoles().contains(UserConstant.MAJOR_ADMIN_ROLE)){
            List<String> roles = new ArrayList<String>();
            roles.add("user");
            user.setRoles(roles);
        }
        user.setIsDelete(0);
        user.setNumber(userAddRequest.getNumber());
        user.setEmail(userAddRequest.getEmail());
        user.setSex(userAddRequest.getSex());
        user.setPhoneNumber(userAddRequest.getPhoneNumber());
        // 检查手机号和邮箱格式是否正确
        if (!CheckUtils.matchesRegex(phoneNumber, email)&&phoneNumber.length() == 11) {
            // 如果手机号或邮箱格式不正确，抛出异常
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }

        // 保存用户信息
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);

        // 返回成功信息和新增的用户数据
        return Result.success("教务教师添加成功", user);
    }

    @ApiOperation("完善信息")
    @Type("完善信息")
    @PutMapping("/complete")
    public Result<String> complete(@RequestBody UserCompleteRequest userCompleteRequest) {
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, userCompleteRequest.getId())
                .eq(User::getIsDelete, 0));

        if (user == null) {
            return Result.error("您操作的用户不存在或已被删除");
        }

        if (userService.getLoginUser().getRoles().contains(UserConstant.DEFAULT_ROLE) ||
                userService.getLoginUser().getRoles().contains(UserConstant.ADMIN_ROLE)) {

            BeanUtils.copyProperties(userCompleteRequest, user, "roles", "isDelete");
//            user.setBirthday(userCompleteRequest.getBirthday());
//            user.setEntryTime(userCompleteRequest.getEntryTime());
//            user.setGraduationDate(userCompleteRequest.getGraduationDate());
            userService.updateById(user);
        } else {
            return Result.error("您不是管理员或者用户本人，无权限操作");
        }

        return Result.success("信息完善成功");
    }

    /**
     * 员工分页查询
     *
     * @param userQueryRequest
     * @return
     */
    @ApiOperation("员工分页查询（仅管理员）")
    @PostMapping("/page")
    public Result<PageResult> page(@RequestBody UserQueryRequest userQueryRequest) {
        log.info("员工分页查询，参数为：{}", userQueryRequest);
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = new Page<>();
        List<String> roles = userService.getLoginUser().getRoles();
        if(roles.contains(UserConstant.DEFAULT_ROLE)){
            userPage = userService.page(new Page<>(current, size),
                    new LambdaQueryWrapper<User>().eq(User::getIsDelete, 0).eq(User::getId, userService.getLoginUser().getId()));
        }else {
            userPage = userService.page(new Page<>(current, size),
                    userService.getQueryWrapper(userQueryRequest));
        }
        return Result.success(new PageResult(userPage.getTotal(), userPage.getRecords()));
    }

    //这里ModelAttribute注解的作用是将请求体中的json数据映射到User对象中
    @Type("导出教师")
    @PostMapping("/excel-output")
    @ApiOperation("导出教师（仅管理员）")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result<String> excel_output(@ModelAttribute UserQueryRequest userQueryRequest ,HttpServletResponse response) throws IOException {
        List<User> userList = new ArrayList<User>();
        List<Long> ids = userQueryRequest.getIds();
        //如果ids不为空，则导出选择的教师信息
        if (ids!= null && !ids.isEmpty()) {
            //如果有筛选条件，优先导出选择的教师信息
            userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getIsDelete, 0).in(User::getId, ids));
        }
        else{
            //如果ids为空，而且没有筛选条件，则导出所有教师信息
            if(Objects.isNull(userQueryRequest.getName())&& Objects.isNull(userQueryRequest.getNumber())&& Objects.isNull(userQueryRequest.getPhoneNumber())&& Objects.isNull(userQueryRequest.getEmail())){
                //则导出所有教师信息
                userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getIsDelete, 0));
            }
            //如果有筛选条件，则导出筛选出的教师信息
            else {
                userList = userService.list(userService.getQueryWrapper(userQueryRequest));
            }
        }
        // 导出教师信息
        List<List<Object>> list2 = userList.stream().map(
                UserController::getList).collect(Collectors.toList());
        // 导出模板
        List<String> header = Arrays.asList("工号", "姓名", "手机号", "邮箱", "职位", "学历", "地址", "性别", "简介","创建人");
        List<List<String>> headList2 = header.stream().map(Arrays::asList).collect(Collectors.toList());
        // 导出
        ExcelUtils.export(response, headList2, list2,null);
        return Result.success("导出成功");
    }


    /**
     * 根据id查询员工信息,如果该员工已被删除，则无法查看
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询员工信息")
    @GetMapping("/{id}")
    public Result<UserVO> getById(@PathVariable Long id) {
        if (id <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if (Objects.equals(user.getIsDelete(), 1)) {
            return Result.error("您操作的员工已被删除，无法查看");
        }
        ThrowUtils.throwIf(user == null, MessageConstant.NOT_FOUND_ERROR);
        UserVO userVO = userService.getUserVO(user);
        return Result.success(userVO);
//        return Result.success(user);
    }

    @ApiOperation("角色全部查询")
    @PostMapping("/list")
    public Result list() {
        return Result.success(UserRoleEnum.toMap());
    }


    @ApiOperation("更改员工角色（仅管理员）")
    @PostMapping("/updateRole")
    public Result updateRole(@RequestBody UserUpdateRoleRequest userUpdateRoleRequest) {
        User loginUser = userService.getLoginUser();
        if (!Objects.equals(loginUser.getRoles().get(0), UserConstant.ADMIN_ROLE)) {
            throw new BaseException("您不是管理员或者对方是管理员，无权限修改角色");
        }
        User user = userService.getById(userUpdateRoleRequest.getId());
        if (user == null) {
            throw new BaseException("查询不到该用户，请联系管理员");
        }
        if(Objects.equals(userService.getLoginUser().getId(), user.getId())){
            throw new BaseException("您不能修改自己的角色");
        }
        user.setRoles(userUpdateRoleRequest.getRoles());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success("角色修改成功");
    }

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @return
     */
    @ApiOperation("更新个人信息")
    @Type("更新个人信息")
    @PutMapping
    public Result update(@RequestBody UserUpdateMyRequest userUpdateMyRequest) {
        //更新个人信息时操作日志记录
        OperLog operLog = userService.setOperLog();
        operLog.setRemark(userService.getLoginUser().getName() + "修改员工：" + userUpdateMyRequest.getName());
        operLogService.save(operLog);

        log.info("编辑员工，请求体为：{}", userUpdateMyRequest);
        if (userUpdateMyRequest == null) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        User user = new User();
        user.setOperUserId(userService.getLoginUser().getId());
        user.setOperUserName(userService.getLoginUser().getName());
        user.setUpdateTime(LocalDateTime.now());//更新时间
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(BaseContext.getCurrentId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success();
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/avatar")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestPart("file") MultipartFile file) {
        log.info("文件上传：{}", file);

        try {
            //原始文件名
            String originalName = file.getOriginalFilename();
            //截取原始文件名的后缀，构造新文件名称
            String objectName = UUID.randomUUID().toString() + originalName.substring(originalName.lastIndexOf("."));
            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            Long userId = userService.getLoginUser().getId();
            User user = new User();
            user.setId(userId);
            user.setAvatar(filePath);
            boolean result = userService.updateById(user);
            if (result) {
                return Result.success();
            }
            return Result.error("更新头像失败");
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        //使用常量来进行引用
        return Result.error(MessageConstant.UPLOAD_FAILED);

    }

    /**
     * 根据id修改员工信息,如果该员工已被删除，则无法修改
     *
     * @param userUpdateRequest 包含更新员工信息的请求对象
     * @param request           HTTP请求对象
     * @return 返回操作结果
     */
    @ApiOperation("根据id修改员工信息（仅管理员）")
    @Type("根据id修改员工信息")
    @PostMapping("/update")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
                                      HttpServletRequest request) {

        // 更新个人信息时操作日志记录
        OperLog operLog = userService.setOperLog();
        operLog.setRemark(userService.getLoginUser().getName() + "修改员工：" + userUpdateRequest.getName());
        operLogService.save(operLog);

        Long id = userUpdateRequest.getId();
        if (id <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id);
        User user1 = userService.getOne(queryWrapper);
        if (user1.getIsDelete() == 1) {
            return Result.error("该员工已被删除，无法修改");
        }

        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, MessageConstant.NOT_FOUND_ERROR);
        user.setUpdateTime(LocalDateTime.now()); // 更新时间
        user.setOperUserId(userService.getLoginUser().getId());
        user.setOperUserName(userService.getLoginUser().getName());
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success("员工信息修改成功", true); // 返回修改成功信息
    }

    @Type("删除员工")
    @PostMapping("/delete")
    @ApiOperation("删除员工（仅管理员）")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        //删除个人信息时操作日志记录
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, deleteRequest.getId());
        User user = userService.getOne(queryWrapper);
        //判断是不是自己创建的用户，如果不是自己创建的用户，则不允许删除
//        if (!Objects.equals(userService.getLoginUser().getId(), user.getCreateUserId())) {
//            throw new BaseException(MessageConstant.NO_AUTH_ERROR);
//        }
        user.setIsDelete(1);
        user.setOperUserId(userService.getLoginUser().getId());
        user.setOperUserName(userService.getLoginUser().getName());

        OperLog operLog = userService.setOperLog();
        operLog.setRemark(userService.getLoginUser().getName() + "删除员工：" + user.getName());
        operLogService.save(operLog);

        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        // 软删除,这里更新isDelete字段为1，表示删除
        return Result.success(userService.removeById(user.getId()));
    }

    /**
     * 导出教师数模版报表（仅管理员）
     */
    @GetMapping("/export")
    @ApiOperation("导出教师数模版报表（仅管理员）")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result<String> export() {
        return Result.success("https://hmleadnews5283.oss-cn-beijing/be9ace0a-3393-43f8-b900-27b6dead95ab.xlsx");
    }



    @PostMapping("/excel-input")
    @ApiOperation("导入教师（仅管理员）")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result<String> excel_input(@RequestBody MultipartFile file, HttpServletRequest request) {
        try {
            String token = request.getHeader(jwtProperties.getTokenName());
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            List<User> userList = ExcelUtils.readExcel(file, userId);
            for (User user : userList) {
                validateUser(user);
                user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
                user.setCreateTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
                user.setIsDelete(0);
                user.setOperUserId(userId);
                user.setCreateUserId(userId);
                user.setOperUserName(userService.getOne(new LambdaQueryWrapper<User>().eq(User::getId, userId)).getName());
                user.setOperUserName(userService.getLoginUser().getName());
            }
            userService.saveBatch(userList);
            return Result.success("导入成功");
        } catch (BaseException e) {
            // 记录日志
            log.error("导入教师时发生错误: ", e);
            throw e;
        } catch (Exception e) {
            // 记录日志
            log.error("解析JWT或保存用户信息时发生错误: ", e);
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
    }

    private void validateUser(User user) {
        String phoneNumber = user.getPhoneNumber();
        String email = user.getEmail();
        if (StringUtils.isBlank(user.getNumber()) || StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getPhoneNumber()) || StringUtils.isBlank(user.getEmail())) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }

        // 检查手机号和邮箱格式是否正确
        if (!CheckUtils.matchesRegex(phoneNumber, email)) {
            // 如果手机号或邮箱格式不正确，抛出异常
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
    }


    private static @NotNull List<Object> getList(User user) {
        List<Object> userInfo = new ArrayList<>();
        userInfo.add(user.getNumber());
        userInfo.add(user.getName());
        userInfo.add(user.getPhoneNumber());
        userInfo.add(user.getEmail());
        userInfo.add(user.getPost());
        userInfo.add(user.getDegree());
        userInfo.add(user.getAddress());

        // 性别转换
        String sex = "男";
        if ("1".equals(user.getSex())) {
            sex = "女";
        }
        userInfo.add(sex);
        userInfo.add(user.getProfile());
        userInfo.add(user.getOperUserName());
        return userInfo;
    }


    @Type("下载教师模板")
    @PostMapping("/template")
    @ApiOperation("下载教师模板（仅管理员）")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result<String> downloadTemplate(HttpServletResponse response) throws IOException {
        List<List<Object>> list = new ArrayList<>();
        List<String> header = Arrays.asList("工号", "姓名", "手机号", "邮箱", "职位", "学历", "地址", "性别", "简介");
        List<List<String>> headList = new ArrayList<>();
        for (String header1 : header) {
            ArrayList<String> arrayList = new ArrayList<>();
            arrayList.add(header1);
            headList.add(arrayList);
        }
        ExcelUtils.export(response, headList, list,null);
        return Result.success("下载成功");
    }

    @GetMapping("/deptTree")
    public Result depTree(Major major) {
        return Result.success(majorService.selectDeptTreeList(major));
    }

}
